package controllers

import (
	"fmt"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	"github.com/samber/lo"
	"goravel/app/models"
	"time"
)

type RecordController struct {
	//Dependent services
}

func NewRecordController() *RecordController {
	return &RecordController{
		//Inject services
	}
}

// Index 工时查询
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         RecordController
// @Accept       json
// @Produce      json
// @Id RecordIndex
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/admin/record [get]
func (r *RecordController) Index(ctx http.Context) http.Response {
	//判断管理员身份
	user := models.User{}
	facades.Auth(ctx).User(&user)
	facades.Orm().Query().Model(&models.User{}).Where("id=?", user.ID).With("Roles").First(&user)
	queries := ctx.Request().Queries()
	records := []models.Record{}
	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}
	if lo.Contains(values, "class_role") || lo.Contains(values, "flow_role") {
		res, _ := httpfacade.NewResult(ctx).SearchByParams(queries, map[string]interface{}{}).ResultPagination(&records, "User", "Ticket.Kind", "Repair", "Ticket.Services")
		return res
	} else {
		res, _ := httpfacade.NewResult(ctx).SearchByParams(queries, map[string]interface{}{
			"user_id": user.ID,
		}).ResultPagination(&records, "User", "Ticket.Kind", "Repair", "Ticket.Services")
		return res
	}
}

func (r *RecordController) Show(ctx http.Context) http.Response {
	return nil
}

func (r *RecordController) Store(ctx http.Context) http.Response {
	return nil
}

func (r *RecordController) Update(ctx http.Context) http.Response {
	return nil
}

func (r *RecordController) Destroy(ctx http.Context) http.Response {
	return nil
}

// YearStatistics 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         RecordController
// @Accept       json
// @Produce      json
// @Id RecordYearStatistics
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  name  query  string  false  "name"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/admin/record/statistics/year [get]
func (r *RecordController) YearStatistics(ctx http.Context) http.Response {
	yearStr := ctx.Request().Input("yearStr")
	//1-传递参数monthStr
	resultData := struct {
		Categories []string `json:"categories"`
		Series     []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
			// 这里可以添加其他可能需要的系列相关属性，比如颜色等，暂时保留为空结构体
		} `json:"series"`
	}{
		Categories: []string{},
		Series: []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
		}{
			{
				Name: "工时",
				Data: []float64{},
			},
		},
	}

	user := models.User{}
	facades.Auth(ctx).User(&user)
	db := facades.Orm().Query()
	//2- 获取当前用户的所有角色
	db.Model(&user).Where("id=?", user.ID).With("Roles").Find(&user)
	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}
	// 执行查询并处理结果
	var records []struct {
		Date  string
		Value float64
	}
	//如果是班长或者作业长，全部查看
	if lo.Contains(values, "flow_role") || lo.Contains(values, "class_role") {
		db.Model(&models.Record{}).
			Select("DATE_FORMAT(created_at,'%Y-%m') as date,sum(score) as value").
			Where("DATE_FORMAT(created_at,'%Y') =?", yearStr).
			Group("DATE_FORMAT(created_at,'%Y-%m')").Find(&records)
	}

	//如果是维修工，只看自己的
	if lo.Contains(values, "employee_role") && !lo.Contains(values, "class_role") && !lo.Contains(values, "flow_role") {

		db.Model(&models.Record{}).Where("user_id", user.ID).
			Select("DATE_FORMAT(created_at,'%Y-%m') as date,sum(score) as value").
			Where("DATE_FORMAT(created_at,'%Y') =?", yearStr).
			Group("DATE_FORMAT(created_at,'%Y-%m')").Find(&records)
	}
	// 填充Categories和Series数据
	for _, record := range records {
		// 将查询到的不同月份添加到Categories列表中（去重处理）
		if !stringInSlice(record.Date, resultData.Categories) {
			resultData.Categories = append(resultData.Categories, record.Date)
		}

		// 将对应月份的工时数据添加到Series的Data列表里
		resultData.Series[0].Data = append(resultData.Series[0].Data, record.Value)
	}

	return httpfacade.NewResult(ctx).Success("", resultData)
}

// MonthStatistics 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         RecordController
// @Accept       json
// @Produce      json
// @Id RecordMonthStatistics
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  name  query  string  false  "name"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/admin/record/statistics/month [get]
func (r *RecordController) MonthStatistics(ctx http.Context) http.Response {
	monthStr := ctx.Request().Input("monthStr")
	// 解析前端传递的月份字符串为时间.Time类型

	// 用于存储最终要返回的数据结构
	resultData := struct {
		Categories []string `json:"categories"`
		Series     []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
			// 这里可以添加其他可能需要的系列相关属性，比如颜色等，暂时保留为空结构体
		} `json:"series"`
	}{
		Categories: []string{},
		Series: []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
		}{
			{
				Name: "工时",
				Data: []float64{},
			},
		},
	}

	user := models.User{}
	facades.Auth(ctx).User(&user)
	db := facades.Orm().Query()

	// 获取当前用户的所有角色
	db.Model(&user).Where("id=?", user.ID).With("Roles").Find(&user)

	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}

	// 执行查询并处理结果
	var records []struct {
		Date  string
		Value float64
	}

	// 如果是班长或者作业长，全部查看
	if lo.Contains(values, "flow_role") || lo.Contains(values, "class_role") {
		db.Model(&models.Record{}).
			Select("DATE_FORMAT(created_at,'%d') as date,sum(score) as value").
			Where("created_at like ? ", monthStr+"%").
			Group("DATE_FORMAT(created_at,'%d')").Find(&records)

	}

	// 如果是维修工，只看自己的
	if lo.Contains(values, "employee_role") && !lo.Contains(values, "class_role") && !lo.Contains(values, "flow_role") {
		db.Model(&models.Record{}).Where("user_id", user.ID).
			Select("DATE_FORMAT(created_at,'%d') as date,sum(score) as value").
			Where("created_at like ? ", monthStr+"%").
			Group("DATE_FORMAT(created_at,'%d')").Find(&records)
	}

	for _, record := range records {
		// 将查询到的不同日期添加到Categories列表中（去重处理）
		if !stringInSlice(record.Date, resultData.Categories) {
			resultData.Categories = append(resultData.Categories, record.Date)
		}

		// 将对应日期的工时数据添加到Series的Data列表里
		for i, series := range resultData.Series {
			if series.Name == "工时" {
				resultData.Series[i].Data = append(resultData.Series[i].Data, record.Value)
			}
		}
	}

	return httpfacade.NewResult(ctx).Success("", resultData)
}

// AnnualStatistics 处理前端请求并返回按指定月份统计数据的函数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         RecordController
// @Accept       json
// @Produce      json
// @Id RecordAnnualStatistics
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  name  query  string  false  "name"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/admin/record/statistics/annual [get]
func (r *RecordController) AnnualStatistics(ctx http.Context) http.Response {
	// 获取当前年份
	currentYear := time.Now().Year()

	// 计算往前推5年的起始年份
	startYear := currentYear - 4

	resultData := struct {
		Categories []string `json:"categories"`
		Series     []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
			// 这里可以添加其他可能需要的系列相关属性，比如颜色等，暂时保留为空结构体
		} `json:"series"`
	}{
		Categories: []string{},
		Series: []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
		}{
			{
				Name: "工时",
				Data: []float64{},
			},
		},
	}

	user := models.User{}
	facades.Auth(ctx).User(&user)
	db := facades.Orm().Query()

	// 获取当前用户的所有角色
	db.Model(&user).Where("id=?", user.ID).With("Roles").Find(&user)

	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}

	// 执行查询并处理结果
	var records []struct {
		Date  string
		Value float64
	}

	// 如果是班长或者作业长，全部查看
	if lo.Contains(values, "flow_role") || lo.Contains(values, "class_role") {
		for year := startYear; year <= currentYear; year++ {
			db.Model(&models.Record{}).
				Select("DATE_FORMAT(created_at, '%Y') as date,sum(score) as value").
				Where("DATE_FORMAT(created_at, '%Y') =?", fmt.Sprintf("%d", year)).
				Group("DATE_FORMAT(created_at, '%Y')").Find(&records)

			// 填充Categories和Series数据
			for _, record := range records {
				// 将查询到的不同年份添加到Categories列表中（去重处理）
				if !stringInSlice(record.Date, resultData.Categories) {
					resultData.Categories = append(resultData.Categories, record.Date)
				}

				// 将对应年份的工时数据添加到Series的Data列表里
				for i, series := range resultData.Series {
					if series.Name == "工时" {
						resultData.Series[i].Data = append(resultData.Series[i].Data, record.Value)
					}
				}
			}

			records = nil // 清空records切片，以便下一年份的查询结果存储
		}
	} else if lo.Contains(values, "employee_role") && !lo.Contains(values, "class_role") && !lo.Contains(values, "flow_role") {
		for year := startYear; year <= currentYear; year++ {
			db.Model(&models.Record{}).Where("user_id", user.ID).
				Select("DATE_FORMAT(created_at, '%Y') as date,sum(score) as value").
				Where("DATE_FORMAT(created_at, '%Y') =?", fmt.Sprintf("%d", year)).
				Group("DATE_FORMAT(created_at, '%Y')").Find(&records)

			// 填充Categories和Series数据
			for _, record := range records {
				// 将查询到的不同年份添加到Categories列表中（去重处理）
				if !stringInSlice(record.Date, resultData.Categories) {
					resultData.Categories = append(resultData.Categories, record.Date)
				}

				// 将对应年份的工时数据添加到Series的Data列表里
				for i, series := range resultData.Series {
					if series.Name == "工时" {
						resultData.Series[i].Data = append(resultData.Series[i].Data, record.Value)
					}
				}
			}

			records = nil // 清空records切片，以便下一年份的查询结果存储
		}
	}

	return httpfacade.NewResult(ctx).Success("", resultData)
}

func (r *RecordController) MiniYearStatistics(ctx http.Context) http.Response {
	yearStr := ctx.Request().Input("yearStr")
	//1-传递参数monthStr
	resultData := struct {
		Categories []string `json:"categories"`
		Series     []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
			// 这里可以添加其他可能需要的系列相关属性，比如颜色等，暂时保留为空结构体
		} `json:"series"`
	}{
		Categories: []string{},
		Series: []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
		}{
			{
				Name: "工时",
				Data: []float64{},
			},
		},
	}

	user := models.User{}
	facades.Auth(ctx).User(&user)
	db := facades.Orm().Query()
	//2- 获取当前用户的所有角色
	db.Model(&user).Where("id=?", user.ID).With("Roles").Find(&user)
	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}
	// 执行查询并处理结果
	var records []struct {
		Date  string
		Value float64
	}
	//如果是班长或者作业长，全部查看
	if lo.Contains(values, "flow_role") || lo.Contains(values, "class_role") {
		db.Model(&models.Record{}).
			Select("DATE_FORMAT(created_at,'%Y-%m') as date,sum(score) as value").
			Where("DATE_FORMAT(created_at,'%Y') =?", yearStr).
			Group("DATE_FORMAT(created_at,'%Y-%m')").Find(&records)
	}

	//如果是维修工，只看自己的
	if lo.Contains(values, "employee_role") && !lo.Contains(values, "class_role") && !lo.Contains(values, "flow_role") {

		db.Model(&models.Record{}).Where("user_id", user.ID).
			Select("DATE_FORMAT(created_at,'%Y-%m') as date,sum(score) as value").
			Where("DATE_FORMAT(created_at,'%Y') =?", yearStr).
			Group("DATE_FORMAT(created_at,'%Y-%m')").Find(&records)
	}
	// 填充Categories和Series数据
	for _, record := range records {
		// 将查询到的不同月份添加到Categories列表中（去重处理）
		if !stringInSlice(record.Date, resultData.Categories) {
			resultData.Categories = append(resultData.Categories, record.Date)
		}

		// 将对应月份的工时数据添加到Series的Data列表里
		resultData.Series[0].Data = append(resultData.Series[0].Data, record.Value)
	}

	return httpfacade.NewResult(ctx).Success("", resultData)
}

// 辅助函数，判断字符串是否在切片中
func stringInSlice(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

// 处理前端请求并返回按指定月份统计数据的函数
func (r *RecordController) MiniMonthStatistics(ctx http.Context) http.Response {
	monthStr := ctx.Request().Input("monthStr")
	// 解析前端传递的月份字符串为时间.Time类型

	// 用于存储最终要返回的数据结构
	resultData := struct {
		Categories []string `json:"categories"`
		Series     []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
			// 这里可以添加其他可能需要的系列相关属性，比如颜色等，暂时保留为空结构体
		} `json:"series"`
	}{
		Categories: []string{},
		Series: []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
		}{
			{
				Name: "工时",
				Data: []float64{},
			},
		},
	}

	user := models.User{}
	facades.Auth(ctx).User(&user)
	db := facades.Orm().Query()

	// 获取当前用户的所有角色
	db.Model(&user).Where("id=?", user.ID).With("Roles").Find(&user)

	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}

	// 执行查询并处理结果
	var records []struct {
		Date  string
		Value float64
	}

	// 如果是班长或者作业长，全部查看
	if lo.Contains(values, "flow_role") || lo.Contains(values, "class_role") {
		db.Model(&models.Record{}).
			Select("DATE_FORMAT(created_at,'%d') as date,sum(score) as value").
			Where("created_at like ? ", monthStr+"%").
			Group("DATE_FORMAT(created_at,'%d')").Find(&records)

	}

	// 如果是维修工，只看自己的
	if lo.Contains(values, "employee_role") && !lo.Contains(values, "class_role") && !lo.Contains(values, "flow_role") {
		db.Model(&models.Record{}).Where("user_id", user.ID).
			Select("DATE_FORMAT(created_at,'%d') as date,sum(score) as value").
			Where("created_at like ? ", monthStr+"%").
			Group("DATE_FORMAT(created_at,'%d')").Find(&records)
	}

	for _, record := range records {
		// 将查询到的不同日期添加到Categories列表中（去重处理）
		if !stringInSlice(record.Date, resultData.Categories) {
			resultData.Categories = append(resultData.Categories, record.Date)
		}

		// 将对应日期的工时数据添加到Series的Data列表里
		for i, series := range resultData.Series {
			if series.Name == "工时" {
				resultData.Series[i].Data = append(resultData.Series[i].Data, record.Value)
			}
		}
	}

	return httpfacade.NewResult(ctx).Success("", resultData)
}

// 处理前端请求并返回按指定月份统计数据的函数
func (r *RecordController) MiniAnnualStatistics(ctx http.Context) http.Response {
	// 获取当前年份
	currentYear := time.Now().Year()

	// 计算往前推5年的起始年份
	startYear := currentYear - 4

	resultData := struct {
		Categories []string `json:"categories"`
		Series     []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
			// 这里可以添加其他可能需要的系列相关属性，比如颜色等，暂时保留为空结构体
		} `json:"series"`
	}{
		Categories: []string{},
		Series: []struct {
			Name string    `json:"name"`
			Data []float64 `json:"data"`
		}{
			{
				Name: "工时",
				Data: []float64{},
			},
		},
	}

	user := models.User{}
	facades.Auth(ctx).User(&user)
	db := facades.Orm().Query()

	// 获取当前用户的所有角色
	db.Model(&user).Where("id=?", user.ID).With("Roles").Find(&user)

	values := []string{}
	for _, role := range user.Roles {
		values = append(values, role.Value)
	}

	// 执行查询并处理结果
	var records []struct {
		Date  string
		Value float64
	}

	// 如果是班长或者作业长，全部查看
	if lo.Contains(values, "flow_role") || lo.Contains(values, "class_role") {
		for year := startYear; year <= currentYear; year++ {
			db.Model(&models.Record{}).
				Select("DATE_FORMAT(created_at, '%Y') as date,sum(score) as value").
				Where("DATE_FORMAT(created_at, '%Y') =?", fmt.Sprintf("%d", year)).
				Group("DATE_FORMAT(created_at, '%Y')").Find(&records)

			// 填充Categories和Series数据
			for _, record := range records {
				// 将查询到的不同年份添加到Categories列表中（去重处理）
				if !stringInSlice(record.Date, resultData.Categories) {
					resultData.Categories = append(resultData.Categories, record.Date)
				}

				// 将对应年份的工时数据添加到Series的Data列表里
				for i, series := range resultData.Series {
					if series.Name == "工时" {
						resultData.Series[i].Data = append(resultData.Series[i].Data, record.Value)
					}
				}
			}

			records = nil // 清空records切片，以便下一年份的查询结果存储
		}
	} else if lo.Contains(values, "employee_role") && !lo.Contains(values, "class_role") && !lo.Contains(values, "flow_role") {
		for year := startYear; year <= currentYear; year++ {
			db.Model(&models.Record{}).Where("user_id", user.ID).
				Select("DATE_FORMAT(created_at, '%Y') as date,sum(score) as value").
				Where("DATE_FORMAT(created_at, '%Y') =?", fmt.Sprintf("%d", year)).
				Group("DATE_FORMAT(created_at, '%Y')").Find(&records)

			// 填充Categories和Series数据
			for _, record := range records {
				// 将查询到的不同年份添加到Categories列表中（去重处理）
				if !stringInSlice(record.Date, resultData.Categories) {
					resultData.Categories = append(resultData.Categories, record.Date)
				}

				// 将对应年份的工时数据添加到Series的Data列表里
				for i, series := range resultData.Series {
					if series.Name == "工时" {
						resultData.Series[i].Data = append(resultData.Series[i].Data, record.Value)
					}
				}
			}

			records = nil // 清空records切片，以便下一年份的查询结果存储
		}
	}

	return httpfacade.NewResult(ctx).Success("", resultData)
}
